package com.tyl.pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ProducerConsumerB {
    public static void main(String[] args) {
        Data2 data=new Data2();

        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A2").start();


        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                try {
                    data.decrease();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B2").start();


        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C2").start();

        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                try {
                    data.decrease();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"D2").start();
    }
}


class Data2{//资源类

    Lock lock=new ReentrantLock();
    Condition condition = lock.newCondition();

    private int number=0;
    //+1
    public  void increment() throws InterruptedException {
        //上锁
        lock.lock();
        try {
            while (number!=0){
                //等待
                condition.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName()+"="+number);
            //告诉别的线程执行结束
            condition.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //解锁
            lock.unlock();
        }
    }
    //-1
    public  void decrease() throws InterruptedException {
        //上锁
        lock.lock();
        try {
            while(number==0){
                //等待
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName()+"="+number);
            //告诉别的线程执行结束
            condition.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //解锁
            lock.unlock();
        }
    }
}